package com.inei.cie;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.inei.cie.dao.PrincipalDao;
import com.inei.cie.utilitarios.Sesion;
import com.inei.cie.utilitarios.Variables;

public class Login_Activity extends Activity {

	public PrincipalDao principal;
	public Variables var;
	public Bundle b;
	public Sesion sesion;
	public EditText etDNI;
	public EditText etContrasena;

	public List<String> lDpto;
	public Spinner spDpto;
	public EditText etClave;
	public Dialog dialogoC;

	public TextView tvAntiguo, tvNuevo;
	public EditText etAntiguo, etNuevo;

	public ProgressDialog progreso;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		// deleteDatabase("cie.db");
		setTitle("CENSO DE INFRAESTRUCTURA EDUCATIVA - CIE 2013");
		IniciarComponentes();
	}

	public void IniciarComponentes() {
		b = new Bundle();
		var = new Variables();

		progreso = new ProgressDialog(this);
		progreso.setCancelable(false);
		progreso.setMax(100);
		progreso.setProgress(0);
		progreso.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progreso.setTitle("Cargando");
		progreso.setMessage("Espere por favor...");
		CargaInicial carga = new CargaInicial();
		carga.execute();
		sesion = new Sesion(this);
		etDNI = (EditText) findViewById(R.id.etDNI);
	}

	public void validarlogin(View v) {
		if (!etDNI.getText().toString().equals(sesion.getDNI())) {
			Toast.makeText(this, "N\u00famero de DNI incorrecto!",
					Toast.LENGTH_SHORT).show();
		} else {
			Intent irPadron = new Intent(this, Carga_Trabajo_Activity.class);
			b.putString(var.DNI, sesion.getDNI());
			b.putString(var.CODIGO_PATRIMONIAL, sesion.getCP());
			irPadron.putExtras(b);
			startActivity(irPadron);
			finish();
		}
	}

	public void salir(View v) {
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.login_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnSalir:
			AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
			dialogo1.setTitle("Importante");
			dialogo1.setMessage("Deseas Salir ?");
			dialogo1.setIcon(android.R.drawable.ic_dialog_alert);
			dialogo1.setCancelable(false);
			dialogo1.setPositiveButton("Si",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialogo1, int id) {
							System.exit(0);
						}
					});

			dialogo1.setNegativeButton("No",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialogo1, int id) {
							return;
						}
					});
			dialogo1.show();
			break;
		case R.id.mnConfigurar:
			CrearDialogoCambio();
			break;
		case R.id.mnCarga:
			CrearDialogoCarga();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void CrearDialogoCarga() {
		dialogoC = new Dialog(this);
		dialogoC.setContentView(R.layout.confirmacion_carga);
		dialogoC.setCancelable(false);
		dialogoC.setTitle("Confirmaci\u00f3n");
		etClave = (EditText) dialogoC.findViewById(R.id.etClave);

		etClave.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.toString().length() >=6 ) {
					if (principal.ConfirmarClave1(s.toString())) {
						spDpto.setEnabled(true);
					} else {
						spDpto.setEnabled(false);
					}
				} else {
					spDpto.setEnabled(false);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		spDpto = (Spinner) dialogoC.findViewById(R.id.spDepartamento);
		spDpto.setEnabled(false);
		Button bCancelar = (Button) dialogoC.findViewById(R.id.bCancelar);
		bCancelar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				dialogoC.cancel();
			}
		});
		Button bAceptar = (Button) dialogoC.findViewById(R.id.bAceptar);
		bAceptar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				if (!principal.ConfirmarClave1(etClave.getText().toString())) {
					Toast.makeText(Login_Activity.this, "Clave incorrecta!",
							Toast.LENGTH_SHORT).show();
				} else if (spDpto.getSelectedItemPosition() != 0) {
					Bundle a = new Bundle();
					Intent irAsignar = new Intent(Login_Activity.this,
							Asignar_Ruta_Activity.class);
					a.putInt(var.DEP, spDpto.getSelectedItemPosition());
					a.putString(var.DNI, sesion.getDNI());
					irAsignar.putExtras(a);
					startActivity(irAsignar);
					dialogoC.cancel();
				} else {
					Toast.makeText(Login_Activity.this,
							"Debe seleccionar un departamento",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, lDpto);
		spDpto.setAdapter(adaptador);
		dialogoC.show();
	}

	public void CrearDialogoCambio() {
		dialogoC = new Dialog(this);
		dialogoC.setContentView(R.layout.confirmacion_cambio);
		dialogoC.setCancelable(false);
		dialogoC.setTitle("Confirmaci\u00f3n");
		etClave = (EditText) dialogoC.findViewById(R.id.etClave);

		etClave.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.toString().length() >=6) {
					if (principal.ConfirmarClave1(s.toString())) {
						tvAntiguo.setVisibility(View.VISIBLE);
						tvNuevo.setVisibility(View.VISIBLE);
						etAntiguo.setVisibility(View.VISIBLE);
						etNuevo.setVisibility(View.VISIBLE);
					} else {
						tvAntiguo.setVisibility(View.GONE);
						tvNuevo.setVisibility(View.GONE);
						etAntiguo.setVisibility(View.GONE);
						etNuevo.setVisibility(View.GONE);
					}
				} else {
					tvAntiguo.setVisibility(View.GONE);
					tvNuevo.setVisibility(View.GONE);
					etAntiguo.setVisibility(View.GONE);
					etNuevo.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		Button bCancelar = (Button) dialogoC.findViewById(R.id.bCancelar);
		bCancelar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				dialogoC.cancel();
			}
		});
		Button bAceptar = (Button) dialogoC.findViewById(R.id.bAceptar);
		bAceptar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				if (!principal.ConfirmarClave1(etClave.getText().toString())) {
					Toast.makeText(Login_Activity.this, "Clave incorrecta!",
							Toast.LENGTH_SHORT).show();
				} else if (!sesion.getDNI().equals(
						etAntiguo.getText().toString())) {
					Toast.makeText(Login_Activity.this,
							"El nmero del DNI antiguo es incorrecto",
							Toast.LENGTH_SHORT).show();
				} else if (etNuevo.getText().toString().trim().length() == 0) {
					Toast.makeText(Login_Activity.this, "Ingrese el nuevo DNI",
							Toast.LENGTH_SHORT).show();
				} else if (etNuevo.getText().toString().trim().length() != 8) {
					Toast.makeText(Login_Activity.this,
							"El nuevo DNI debe tener 8 d\u00edgitos",
							Toast.LENGTH_SHORT).show();
				} else {
					sesion.prepararEdit();
					sesion.setDNI(etNuevo.getText().toString());
					sesion.terminarEdit();
					dialogoC.cancel();
					Calendar c = Calendar.getInstance();
					SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
					String fecha = df.format(c.getTime());
					SimpleDateFormat dh = new SimpleDateFormat("HH:mm:ss");
					String hora = dh.format(c.getTime());
					Log.i("FECHA REGISTRO", fecha);
					Log.i("FECHA REGISTRO", hora);
					principal.GuardarDNI(sesion.getDNI(),sesion.getCP(),fecha,hora);
				}
			}
		});

		tvAntiguo = (TextView) dialogoC.findViewById(R.id.tvAntiguo);
		tvNuevo = (TextView) dialogoC.findViewById(R.id.tvNuevo);

		etAntiguo = (EditText) dialogoC.findViewById(R.id.etAntiguo);
		etNuevo = (EditText) dialogoC.findViewById(R.id.etNuevo);

		tvAntiguo.setVisibility(View.GONE);
		tvNuevo.setVisibility(View.GONE);
		etAntiguo.setVisibility(View.GONE);
		etNuevo.setVisibility(View.GONE);

		dialogoC.show();
	}

	public class CargaInicial extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			progreso.show();
		}

		@Override
		protected Void doInBackground(Void... params) {

			principal = new PrincipalDao(Login_Activity.this);
			lDpto = principal.ListadoNombresDpto();
			lDpto.add(0, "SELECCIONAR");
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			progreso.dismiss();
		}

	}

}
